package cn.ztuo.bitrade.config;

import cn.ztuo.bitrade.Trader.CoinTrader;
import cn.ztuo.bitrade.Trader.CoinTraderFactory;
import cn.ztuo.bitrade.entity.ExchangeOrder;
import cn.ztuo.bitrade.entity.ExchangeOrderDetail;
import cn.ztuo.bitrade.service.ExchangeOrderDetailService;
import cn.ztuo.bitrade.service.ExchangeOrderService;
import cn.ztuo.bitrade.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class CoinTraderEvent implements ApplicationListener<ContextRefreshedEvent> {
    private Logger log = LoggerFactory.getLogger(CoinTraderEvent.class);
    @Autowired
    CoinTraderFactory coinTraderFactory;
    @Autowired
    private ExchangeOrderService exchangeOrderService;
    @Autowired
    private ExchangeOrderDetailService exchangeOrderDetailService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        log.info("======initialize coinTrader======");
        HashMap<String, CoinTrader> traders = coinTraderFactory.getTraderMap();
        traders.forEach((symbol, trader) -> {
            //查询交易对的所有挂单数据
            List<ExchangeOrder> orders = exchangeOrderService.findAllTradingOrderBySymbol(symbol);
            //交易的订单集合
            List<ExchangeOrder> tradingOrders = new ArrayList<>();
            //已完成的订单集合
            List<ExchangeOrder> completedOrders = new ArrayList<>();
            orders.forEach(order -> {
                //交易的数量
                BigDecimal tradedAmount = BigDecimal.ZERO;
                //交易的金额
                BigDecimal turnover = BigDecimal.ZERO;
                //查询某订单的成交详情
                List<ExchangeOrderDetail> details = exchangeOrderDetailService.findAllByOrderId(order.getOrderId());
                //order.setDetail(details);
                for (ExchangeOrderDetail trade : details) {
                    //数量加数量
                    tradedAmount = tradedAmount.add(trade.getAmount());
                    //交易的金额加  数量乘以价格
                    turnover = turnover.add(trade.getAmount().multiply(trade.getPrice()));
                }
                //把交易的数量set 进订单
                order.setTradedAmount(tradedAmount);
                //把交易的金额set 进订单
                order.setTurnover(turnover);
                //判断订单是否撮合完成
                if (!order.isCompleted()) {
                    //没完成接着循环
                    tradingOrders.add(order);
                } else {
                    //完成了kafka 推送通知  处理完成的业务
                    completedOrders.add(order);
                }
            });
            log.info("trader={}", trader);
            //线程处理未完成的订单  jhh
            trader.trade(tradingOrders);
            //判断已完成的订单发送消息通知
            if (completedOrders.size() > 0) {
                kafkaTemplate.send("exchange-order-completed", symbol, JSON.toJSONString(completedOrders));
            }
            trader.setReady(true);
        });
    }

}
